const express = require('express');
const router = express.Router();
const { v4: uuidv4 } = require('uuid');
const dayjs = require('dayjs');


// --- Mock Database ---
let mockTradeOrders = [
  {
    key: 'T001',
    type: '组合调仓',
    subject: '稳健增长FOF组合',
    advisor: '张三',
    timestamp: '2025-06-21 10:30',
    status: 'pending',
    details: '为152名客户进行调仓，涉及3只基金。'
  },
  {
    key: 'T002',
    type: '差错处理',
    subject: '客户 王先生 (CUST-007)',
    advisor: '李四',
    timestamp: '2025-06-22 09:45',
    status: 'pending',
    details: '将失败标的“华夏成长混合”替换为“嘉实新兴产业股票”。'
  },
  {
    key: 'T003',
    type: '账户调仓',
    subject: '客户 赵先生 (CUST-113)',
    advisor: '张三',
    timestamp: '2025-06-23 16:20',
    status: 'completed',
    details: '根据独立调仓计划，调整客户持仓权重。'
  },
  {
    key: 'T004',
    type: '组合调仓',
    subject: '全球科技先锋策略',
    advisor: '王五',
    timestamp: '2025-06-24 14:00',
    status: 'rejected',
    rejectReason: '市场波动较大，建议暂缓调仓。'
  },
];

let mockSettlements = [
    { key: 'S001', tradeOrderId: 'T003', clientId: 'CUST-113', clientName: '赵先生', fundCode: 'F005', fundName: '广发纳斯达克100ETF', type: '买入', amount: 12000, price: 3.45, quantity: 3478.26, timestamp: '2024-05-20 17:01:45', status: 'success' },
    { key: 'S002', tradeOrderId: 'T003', clientId: 'CUST-042', clientName: '李女士', fundCode: 'F002', fundName: '易方达消费行业', type: '买入', amount: 8000, price: 2.15, quantity: 3720.93, timestamp: '2024-05-21 14:05:12', status: 'failure', failure_reason: '客户账户余额不足' },
    { key: 'S003', tradeOrderId: 'T003', clientId: 'CUST-007', clientName: '王先生', fundCode: 'F001', fundName: '华夏成长混合', type: '卖出', amount: 5000, price: 1.25, quantity: 4000, timestamp: '2024-05-21 14:05:10', status: 'failure', failure_reason: '基金状态禁止赎回' },
];
// --- End Mock Database ---


// === Trade Order Management (交易单管理) ===

// GET all trade orders (can be filtered by status)
router.get('/trade-orders', (req, res) => {
    const { status } = req.query;
    if (status) {
        res.json(mockTradeOrders.filter(o => o.status === status));
    } else {
        res.json(mockTradeOrders);
    }
});

// POST to approve a trade order
router.post('/trade-orders/:key/approve', (req, res) => {
    const { key } = req.params;
    const order = mockTradeOrders.find(o => o.key === key);
    if (order) {
        order.status = 'completed';
        res.json(order);
    } else {
        res.status(404).json({ message: 'Trade order not found' });
    }
});

// POST to reject a trade order
router.post('/trade-orders/:key/reject', (req, res) => {
    const { key } = req.params;
    const { reason } = req.body;
    const order = mockTradeOrders.find(o => o.key === key);
    if (order) {
        order.status = 'rejected';
        order.rejectReason = reason;
        res.json(order);
    } else {
        res.status(404).json({ message: 'Trade order not found' });
    }
});


// === Settlement Management (交割单管理) ===

// GET all settlement records with filtering
router.get('/settlements', (req, res) => {
    const { clientId, fundCode, status, dateRange } = req.query;
    let data = [...mockSettlements];

    if (clientId) {
        data = data.filter(item => item.clientId && item.clientId.includes(clientId));
    }
    if (fundCode) {
        data = data.filter(item => item.fundCode && item.fundCode.includes(fundCode));
    }
    if (status) {
        data = data.filter(item => item.status === status);
    }
    if (dateRange) {
        const [start, end] = JSON.parse(dateRange);
        data = data.filter(item => {
            const itemDate = dayjs(item.timestamp);
            return itemDate.isAfter(dayjs(start)) && itemDate.isBefore(dayjs(end));
        });
    }
    
    res.json(data);
});

// === Error Handling (差错处理) ===

// GET failed settlement records
router.get('/settlements/failed', (req, res) => {
    const failedTrades = mockSettlements
        .filter(s => s.status === 'failure')
        .map(s => ({
            key: s.key,
            clientId: s.clientId,
            clientName: s.clientName,
            portfolioName: '稳健增长FOF组合', // Mock data
            failedFund: s.fundName,
            tradeType: s.type,
            amount: `${s.amount}元`,
            reason: s.failure_reason,
            status: 'unprocessed'
        }));
    res.json(failedTrades);
});

// POST a correction for a failed trade
router.post('/error-correction', (req, res) => {
    const { originalSettlementKey, replacementFund } = req.body;
    
    // In a real app, you'd find the original, mark it as resolved, and create a new trade order.
    const newOrder = {
        key: `T${String(mockTradeOrders.length + 1).padStart(3, '0')}`,
        type: '差错处理',
        subject: `客户 (修正)`,
        advisor: '系统',
        timestamp: new Date().toISOString().replace('T', ' ').substring(0, 16),
        status: 'pending',
        details: `修正失败交易 ${originalSettlementKey}，替换为 ${replacementFund}。`
    };
    mockTradeOrders.push(newOrder);
    res.status(201).json(newOrder);
});


// === Rebalance Request Handling ===

// POST a portfolio rebalance plan
router.post('/portfolio-rebalance', (req, res) => {
    const { portfolioName } = req.body;
    const newOrder = {
        key: `T${String(mockTradeOrders.length + 1).padStart(3, '0')}`,
        type: '组合调仓',
        subject: portfolioName,
        advisor: '张三', // Assume current user
        timestamp: new Date().toISOString().replace('T', ' ').substring(0, 16),
        status: 'pending',
        details: `对组合 ${portfolioName} 发起批量调仓。`
    };
    mockTradeOrders.push(newOrder);
    res.status(201).json(newOrder);
});

// POST an account rebalance plan
router.post('/account-rebalance', (req, res) => {
    const { clientId, clientName } = req.body;
    const newOrder = {
        key: `T${String(mockTradeOrders.length + 1).padStart(3, '0')}`,
        type: '账户调仓',
        subject: `客户 ${clientName} (${clientId})`,
        advisor: '李四', // Assume current user
        timestamp: new Date().toISOString().replace('T', ' ').substring(0, 16),
        status: 'pending',
        details: `对客户 ${clientName} 发起独立调仓。`
    };
    mockTradeOrders.push(newOrder);
    res.status(201).json(newOrder);
});

module.exports = router;